package test;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.jar.*;

public class JarExplorer {

	private String adresseJar;
	
	private ArrayList<JarEntry> entreesJar = new ArrayList<JarEntry>();
	
	public JarExplorer() throws IOException {
		Scanner sc = new Scanner(System.in);
		System.out.println("Veuillez saisir le chemin complet du jar :");
		String nomUrl = "jar:file:" + sc.nextLine() + "!/";
		adresseJar = nomUrl;
		URL url = new URL(nomUrl);
		JarURLConnection conn = (JarURLConnection)url.openConnection();
		Enumeration<JarEntry> e = conn.getJarFile().entries();
		while (e.hasMoreElements()) {
			JarEntry entree = (JarEntry)e.nextElement();
			entreesJar.add(entree);
		}
	}

	public void setAdresseJar(String adresseJar) {
		this.adresseJar = adresseJar;
	}

	public String getAdresseJar() {
		return adresseJar;
	}

	public void setEntreesJar(ArrayList<JarEntry> entreesJar) {
		this.entreesJar = entreesJar;
	}

	public ArrayList<JarEntry> getEntreesJar() {
		return entreesJar;
	}
	
	public boolean isPackage(String name, ArrayList<JarEntry> enu){
		for(int i = 0; i < enu.size(); i++) {
			JarEntry pizza = enu.get(i);
			if (pizza.getName().startsWith(name) == true){
				if (pizza.isDirectory() == false){
					if (pizza.getName().replaceFirst(name, "").contains("/") == false && pizza.getName().replaceFirst(name, "").endsWith(".class") == true){
						return true;
					}
				}
			}
		}
		return false ;
	}
	
	public ArrayList<JarEntry> getPackagesNames(){
		ArrayList<JarEntry> packagesNames = new ArrayList<JarEntry>();
		for (int i=0;i<this.entreesJar.size();i++ ){
			if (this.entreesJar.get(i).isDirectory()){
				if (this.isPackage(this.entreesJar.get(i).getName(),this.entreesJar)){
					packagesNames.add(this.entreesJar.get(i));
				}
			}
		}
		return packagesNames;
	}
	
	public ArrayList<JarEntry> getPkgClasses(String name){
		ArrayList<JarEntry> classesNames = new ArrayList<JarEntry>();
		for (int i=0;i<this.entreesJar.size();i++ ){
			if (this.entreesJar.get(i).isDirectory() == false){
				if (this.entreesJar.get(i).getName().startsWith(name) && this.entreesJar.get(i).getName().endsWith(".class")){
					if (this.entreesJar.get(i).getName().replaceFirst(name, "").contains("/") == false){
						classesNames.add(this.entreesJar.get(i));
					}
				}
			}
		}
		return classesNames;
	}
		
}
